var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');



//引入路由
var indexRouter = require('./routes/index');
var adminRouter = require('./routes/admin');

var app = express();

const session = require('express-session');
app.use(session({
    name: 'uid', // 这里是cookie的name，默认是connect.sid
    secret: 'my_session_secret', // 建议使用 128 个字符的随机字符串
    resave: false,               ///强制保存session，即使它没有变化
    saveUninitialized: true,     //保存未初始化的值,减轻服务器压力
    rolling:false, //每次响应是否重新设置cookie的maxAge., true
    cookie: { maxAge: 60 * 1000 *60 *24*7, httpOnly: true }  //60秒
}));


app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//挂载路由
app.use(indexRouter);

app.use((req, res, next) => {
  // 如果不是登录页面 并且没有登录则跳转登录页面 ,否则放行
  if (req.originalUrl != '/admin/login' && !req.session.user) {
      res.redirect('/admin/login');
  }
  next();
});

app.use('/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) { 
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};  
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
